import Q  from './vendor/q';
import utils  from './utils';
import events  from  './events';
import Task  from './task';

function PostObjectTask() {
    Task.apply(this, arguments);
    this._policyManager = null;
}

utils.inherits(PostObjectTask, Task);

PostObjectTask.prototype.setPolicyManager = function (policyManager) {
    this._policyManager = policyManager;
};

PostObjectTask.prototype.start = function (opt_maxRetries) {
    if (this.aborted) {
        return Q.resolve();
    }
    var self = this;
    var dispatcher = this.eventDispatcher;
    var file = this.options.file;
    var bucket = this.options.bucket;
    var object = this.options.object;
    var config = this.client.config;
    return this._policyManager.get(bucket)
        .then(function (payload) {
            // http://bj.bcebos.com/<bucket>/ 的上传请求改成
            // http://<bucket>.bj.bcebos.com
            var url = config.endpoint + '/' + bucket + '/'; //config.endpoint.replace(/^(https?:\/\/)/, '$1' + bucket + '.');
            var fields = {
                'key': object,
                'policy': payload.policy,
                'signature': payload.signature,
                'accessKey': payload.accessKey,
                'success-action-status': '201'
            };
            return self._sendPostRequest(url, fields, file);
        })
        .then(function (response) {
            response.body.bucket = bucket;
            response.body.object = object;
            response.body.key = object;
            dispatcher.dispatchEvent(events.kFileUploaded, [file, response]);
        })
        .catch(function (error) {
            var eventType = self.aborted ? events.kAborted : events.kError;
            dispatcher.dispatchEvent(eventType, [error, file]);
        });
};

PostObjectTask.prototype._sendPostRequest = function (url, fields, file) {
    var self = this;
    var dispatcher = this.eventDispatcher;
    var deferred = Q.defer();
    var formData = {};
    for(var key in fields){
        if(fields[key] == null) return;
        formData[key] = fields[key];
    }
    var headers = {};
    var xhr = wx.uploadFile({
        url : url,
        filePath : file.name,
        name : 'file',
        formData : formData,
        success : function(res){
              if(res.statusCode >= 200 && res.statusCode < 300){
                  deferred.resolve({
                      http_headers : headers,
                      body:{}
                  });
              }else{
                  deferred.reject(new Error('Invalid response statusCode' + res.statusCode));
              }  
        },
        fail :function(error){
            deferred.reject(error);
        }
    });
    /**
     * 上传返回头部信息监听
     */
    if(xhr.onHeadersReceived){
        xhr.onHeadersReceived(function(header){
            headers = header;
        });
    }
    if(xhr.onProgressUpdate){
        /**
         * 上传进度监听
         */
        xhr.onProgressUpdate(function(progress,totalBytesSent,totalBytesExpectedToSend){
            self.networkInfo.loadedBytes = totalBytesSent - file._previousLoaded;
            file._previousLoaded = totalBytesSent;
            dispatcher.dispatchEvent(events.kNetworkSpeed, self.networkInfo.dump());
            dispatcher.dispatchEvent(events.kUploadProgress, [file, progress, null]);
        });
    }
    return deferred.promise;
};

export default PostObjectTask
